# -*- coding: utf-8 -*-
# 请认准 VNPY官方网站 http://www.vnpy.cn
import webbrowser
import numpy as np
import pyqtgraph as pg
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from pyqtgraph import QtCore, QtGui
from PyQt5.QtWidgets import QVBoxLayout, QWidget, QDialog, QPushButton, QMessageBox
import time
import os
import globalvar
import pandas as pd
import threading
# K线图
global lasttime, kid
kid = 0
lasttime = -1.0


class CandlestickItem(pg.GraphicsObject):
    def __init__(self, data):
        pg.GraphicsObject.__init__(self)
        self.data = data  ## data must have fields: time, open, close, min, max
        self.generatepicture()

    def generatepicture(self):
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
        # print('输出A：'+str(len(self.data)))
        if len(self.data) == 0:
            pass
        elif len(self.data) == 1:
            if str(self.data) == '[(0, 0, 0, 0, 0, 0, 0)]':
                return
            else:
                w = 0.5
                for (t, tradingday, klinetime, open, close, min, max) in self.data:
                    QApplication.processEvents()
                    p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
                    if open > close:
                        p.setBrush(pg.mkBrush('g'))
                    else:
                        p.setBrush(pg.mkBrush('r'))
                    p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))
        else:
            w = (self.data[1][0] - self.data[0][0]) / 3
            for (t, tradingday, klinetime, open, close, min, max) in self.data:
                QApplication.processEvents()
                p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
                if open > close:
                    p.setBrush(pg.mkBrush('g'))
                else:
                    p.setBrush(pg.mkBrush('r'))
                p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))
        p.end()

    def paint(self, p, *args):
        p.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        return QtCore.QRectF(self.picture.boundingRect())


class CandlestickItem2(pg.GraphicsObject):
    def __init__(self, data):
        pg.GraphicsObject.__init__(self)
        self.data = data  ## data must have fields: time, open, close, min, max
        self.generatepicture()

    def generatepicture(self):
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
        # print('输出A：'+str(len(self.data)))
        if len(self.data) == 0:
            pass
        elif len(self.data) == 1:
            if str(self.data) == '[(0, 0, 0, 0, 0, 0, 0)]':
                return
            else:
                w = 0.5
                for (t, tradingday, klinetime, open, close, min, max) in self.data:
                    QApplication.processEvents()
                    p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
                    if open > close:
                        p.setBrush(pg.mkBrush('g'))
                    else:
                        p.setBrush(pg.mkBrush('r'))
                    p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))
        else:
            w = (self.data[1][0] - self.data[0][0]) / 3
            for (t, tradingday, klinetime, open, close, min, max) in self.data:
                QApplication.processEvents()
                p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
                if open > close:
                    p.setBrush(pg.mkBrush('g'))
                else:
                    p.setBrush(pg.mkBrush('r'))
                p.drawRect(QtCore.QRectF(t - w, open, w * 2, close - open))
        p.end()

    def paint(self, p, *args):
        p.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        return QtCore.QRectF(self.picture.boundingRect())


data_market = []
# pyqtgraph资金曲线图
data_backtest = []

# pyqtgraph K线
# 数据对应关系 (id, TradingDay, KlineTime,  open, close, min, ma).
data_kline = [(0, 0, 0, 0, 0, 0, 0), ]
count = 0

tradestate = 0

global markettj
markettj = 0
global config


class Ui_MainWindow(object):
    global markettj

    def callback_kline(self, msg):
        pass

    def mounthyear4(self, thisdate, add):
        year = int(thisdate * 0.01)
        mounth = thisdate - year * 100
        mounth = mounth + add
        if mounth > 12:
            mounth = mounth - 12
            year = year + 1
        thisdate = year * 100 + mounth
        return thisdate

    def mounthyear3(self, thisdate, add):
        year = int(thisdate * 0.01)
        y = int(thisdate * 0.001)
        mounth = thisdate - year * 100
        mounth = mounth + add
        if mounth > 12:
            mounth = mounth - 12
            year = year + 1
        thisdate = year * 100 + mounth
        thisdate = thisdate - 1000 * y
        return thisdate

    def MakeInsutrumentID(self, instrumentMain, instrumentName, exchange, templist):
        global tempdate
        returnvalue = 0
        savedate = time.strftime("%Y%m%d", time.localtime())
        tvs = (int(float(savedate) * 0.000001)) * 1000000
        tempdate = int((float(savedate) - float(tvs)) * 0.01)
        tj = 0
        for j in range(12):
            if exchange == 'INE':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'CFFEX':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'SHFE':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'DCE':
                returnvalue = self.mounthyear4(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
            elif exchange == 'CZCE':
                returnvalue = self.mounthyear3(tempdate, j)
                if len(instrumentMain) > 0:
                    templist.append(instrumentMain + str(returnvalue))
        return returnvalue

    dict_period = {'K线周期: M1': '1min', 'K线周期: M3': '3min',
                   'K线周期: M5': '5min', 'K线周期: M10': '10min',
                   'K线周期: M15': '15min', 'K线周期: M30': '30min',
                   'K线周期: M60': '60min', 'K线周期: M120': '120min',
                   'K线周期: D1': '1d'
                   }

    dict_period2 = {1: '1min', 3: '3min',
                    5: '5min', 10: '10min',
                    15: '15min', 30: '30min',
                    60: '60min', 120: '120min',
                    9999001: '1d'
                    }

    dict_period3 = {'K线周期: M1': 1, 'K线周期: M3': 3,
                    'K线周期: M5': 5, 'K线周期: M10': 10,
                    'K线周期: M15': 15, 'K线周期: M30': 30,
                    'K线周期: M60': 60, 'K线周期: M120': 120,
                    'K线周期: D1': 9999001
                    }

    dict_comboBox_kline_index = {1: 0, 3: 1,
                                 5: 2, 10: 3,
                                 15: 4, 30: 5,
                                 60: 6, 120: 7,
                                 9999001: 8
                                 }

    # 从服务器获取M1周期K线数据
    def GetKlineFromeServer(self):
        global data_kline, data_market
        self.plt_kline.clear()
        data_kline = [(0, 0, 0, 0, 0, 0, 0), ]
        globalvar.data_kline_M1.clear()
        data_market.clear()
        thisInstrument = str(globalvar.selectinstrumenid)
        try:
            # 清空该合约 DataFrame 数据
            if len(globalvar.dict_dataframe_kline_M1[thisInstrument]) > 0:
                globalvar.dict_dataframe_kline_M1[thisInstrument].drop(
                    globalvar.dict_dataframe_kline_M1[thisInstrument].index, inplace=True)
        except Exception as e:
            print("dict_dataframe_kline_M1 is empty: " + repr(e))
            globalvar.dict_dataframe_kline_M1[thisInstrument] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [], 'vol': []}, index=[])

        self.plt_kline.enableAutoRange(axis='y')
        self.plt_kline.setAutoVisible(y=False)
        # print('globalvar.thistoday: '+ str(globalvar.thistoday))
        # if globalvar.thistoday == 0:
        globalvar.thistoday = globalvar.vk.GetTradingDay()
        if globalvar.thistoday < 19000000:
            print("起始交易日错误" + str(globalvar.thistoday))
            return
        if globalvar.klineserverstate == 0:
            self.updateklineUi(globalvar.selectinstrumenid)
        elif globalvar.klineserverstate == 1:
            # 从服务器获取当日M1周期K线数据
            self.comboBox_kline.setCurrentIndex(self.dict_comboBox_kline_index[globalvar.selectperiod])
            # K线图切换到最后一次保存的周期，重新绘图
            self.ChangePeriodCharts_klineperiod(globalvar.selectperiod)
            globalvar.vk.GetServerKline(thisInstrument, int(globalvar.thistoday))
            self.UpdateKlineUIFromFile(globalvar.selectinstrumenid, int(globalvar.thistoday))
        elif globalvar.klineserverstate == 2:
            # 从服务器获取多日M1周期K线数据（需Plus会员）
            self.comboBox_kline.setCurrentIndex(self.dict_comboBox_kline_index[globalvar.selectperiod])
            # K线图切换到最后一次保存的周期，重新绘图
            self.ChangePeriodCharts_klineperiod(globalvar.selectperiod)
            if globalvar.vk.GetServerMultiKline(thisInstrument, int(globalvar.thistoday), 10,
                                                globalvar.Plus_UserName, globalvar.Plus_Password) == 1:
                self.UpdateMultiKlineUIFromFile(globalvar.selectinstrumenid, int(globalvar.thistoday))
                globalvar.PlusAuthState = 1
            else:
                webbrowser.open('http://www.vnpy.cn/qplus.html')

    # 从内存获取K线 M1周期数据
    def GetKlineFromeMemory(self, df, period_type):
        global data_kline, data_market
        self.plt_kline.clear()
        data_kline = [(0, 0, 0, 0, 0, 0, 0), ]
        globalvar.data_kline_M1.clear()
        data_market.clear()
        thisInstrument = str(globalvar.selectinstrumenid)
        self.plt_kline.enableAutoRange(axis='y')
        self.plt_kline.setAutoVisible(y=False)
        if globalvar.thistoday == 0:
            globalvar.thistoday = globalvar.vk.GetTradingDay()
        if globalvar.thistoday < 19000000:
            print("起始交易日错误" + str(globalvar.thistoday))
            return
        self.UpdateKlineChartsBycombox(globalvar.selectinstrumenid, period_type, df)

    # 由M1周期数据，通过DataFrame方式生成选中combox 周期的K线数据，并更新K线图表
    def UpdateKlineChartsBycombox(self, InstrumentID, period_type, df):
        global data_kline_M1
        data_kline_M1 = [(0, 0, 0, 0, 0, 0, 0), ]
        try:
            cid = 1
            globalvar.ticklist = []
            for index, row in df.iterrows():
                QApplication.processEvents()
                # if lastdatetime != str(row['datetime']):
                # ld = line.split(',')
                temp = (cid,
                        float(str(row['tradingday'])),
                        float(str(row['klinetime'])),
                        float(str(row['open'])),
                        float(str(row['close'])),
                        float(str(row['low'])),
                        float(str(row['high'])))
                globalvar.data_kline_M1.append(temp)

                tempstr = str(int(float(row['klinetime']) * 10000))
                tempstr_list = list(tempstr)
                tempstr_list.insert(len(tempstr_list) - 2, ':')
                tempstr = ''.join(tempstr_list)
                globalvar.ticklist.append(str(row['tradingday']) + "\n" + tempstr)

                cid = cid + 1
            self.plt_kline.removeItem(self.item)
            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
            try:
                self.plt_kline.addItem(self.item)
            except Exception as e:
                print("UpdateKlineChartsBycombox Error:" + repr(e))

            # 横坐标刻度
            xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
            xdict = dict(enumerate(globalvar.ticklist))
            xax.setTicks([xdict.items()])
            # 根据M1周期K线合成M3周期K线数据
            # module_combinekline.ComposeKlineUpdate(InstrumentID, "3min")
        except Exception as e:
            print("UpdateKlineChartsBycombox Error:" + repr(e))

    def InitKlineDataFrame(self, InstrumentID):
        try:
            if isinstance(globalvar.dict_dataframe_kline_M3[InstrumentID], pd.DataFrame):
                pass
        except Exception as e:
            globalvar.dict_dataframe_kline_M3[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M5[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M10[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M15[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M30[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M60[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_M120[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            globalvar.dict_dataframe_kline_D1[InstrumentID] = pd.DataFrame(
                {'datetime': [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [], 'low': [], 'high': [],
                 'vol': []}, index=[])
            print("InitKlineDataFrame Error:" + repr(e))

    # DataFrame数据预处理，由M1周期数据，通过DataFrame方式生成选中combox 周期的K线数据，并更新K线图表
    # 根据M1 K线数据生成多个周期的K线数据，以DataFrame格式存储在dataframe_kline目录下
    def combineklineUpdateCharts(self, InstrumentID, period_type):
        # 初始化该合约DataFrame类型的除M1周期以外所有周期的K线数据变量
        self.InitKlineDataFrame(InstrumentID)
        dict_period_dataframe_kline = {'K线周期: M1': globalvar.dict_dataframe_kline_M1[InstrumentID],
                                       'K线周期: M3': globalvar.dict_dataframe_kline_M3[InstrumentID],
                                       'K线周期: M5': globalvar.dict_dataframe_kline_M5[InstrumentID],
                                       'K线周期: M10': globalvar.dict_dataframe_kline_M10[InstrumentID],
                                       'K线周期: M15': globalvar.dict_dataframe_kline_M15[InstrumentID],
                                       'K线周期: M30': globalvar.dict_dataframe_kline_M30[InstrumentID],
                                       'K线周期: M60': globalvar.dict_dataframe_kline_M60[InstrumentID],
                                       'K线周期: M120': globalvar.dict_dataframe_kline_M120[InstrumentID],
                                       'K线周期: D1': globalvar.dict_dataframe_kline_D1[InstrumentID]
                                       }

        try:

            if not os.path.exists(("dataframe_kline\\" + InstrumentID)):
                os.mkdir("dataframe_kline\\" + InstrumentID)
            globalvar.dict_dataframe_kline_M1[InstrumentID].to_csv(
                "dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index=False)
            data = pd.read_csv("dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index_col='datetime',
                               parse_dates=True)

            grouper = data.groupby(
                [pd.Grouper(freq=period_type), 'recordid', 'tradingday', 'klinetime', 'instrumentid', 'open', 'close',
                 'low', 'high',
                 'vol'])

            df = pd.DataFrame(grouper['instrumentid'].count())
            df.rename(columns={'instrumentid': 'count'}, inplace=True)
            df.reset_index(inplace=True)
            del df['count']

            df2 = pd.DataFrame(
                {"datetime": [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [],
                 'low': [], 'high': [],
                 'vol': []}, index=[])

            lastdatetime = ""
            high = 0
            low = 0
            open = 0
            close = 0
            vol = 0
            instrumentid = ""
            datetime = ""
            tradingday = ""
            klinetime = ""
            recordid = 1

            for index, row in df.iterrows():
                QApplication.processEvents()
                if lastdatetime != str(row['datetime']):
                    if open > 0:
                        tempdata = {"datetime": datetime, "recordid": '{:0>8s}'.format(str(recordid)),
                                    "tradingday": tradingday, "klinetime": klinetime,
                                    "instrumentid": instrumentid,
                                    "open": open, "close": close, "low": low, "high": high, "vol": vol}
                        df2 = df2.append(tempdata, ignore_index=True)
                    recordid = int(row['recordid'])
                    open = float(row['open'])
                    low = float(row['low'])
                    high = float(row['high'])
                    close = float(row['close'])
                    vol = int(row['vol'])
                    lastdatetime = str(row['datetime'])
                    lastclose = row['close']
                    datetime = row['datetime']
                    instrumentid = row['instrumentid']
                    tradingday = row['tradingday']
                    klinetime = row['klinetime']
                else:
                    recordid = int(row['recordid'])
                    low = min(low, float(row['low']))
                    high = max(high, float(row['high']))
                    close = float(row['close'])
                    vol = vol + int(row['vol'])

            df2 = df2.sort_values(by='recordid')
            df2.to_csv("dataframe_kline\\" + InstrumentID + "\\kline_" + period_type + ".csv", index=True)
            dict_period_dataframe_kline[period_type] = df2.copy()
            # 从内存获取K线数据并更新K线图表
            self.GetKlineFromeMemory(dict_period_dataframe_kline[period_type], period_type)

        except Exception as e:
            print("combineklineUpdateCharts Error:" + repr(e))

    # 需要生成合约&周期的K线数据状态
    # 合约为dict,周期为list
    dict_instrument_period = {}

    # DataFrame数据预处理，由M1周期数据，后台方式计算，通过DataFrame方式生成选中combox 周期的K线数据，
    # 并根据M1 K线数据生成多个周期的K线数据，以DataFrame格式存储在dataframe_kline目录下
    def combineklineBackgroundCal(self, InstrumentID):
        # 初始化该合约DataFrame类型的除M1周期以外所有周期的K线数据变量
        self.InitKlineDataFrame(InstrumentID)
        dict_period_dataframe_kline = {'K线周期: M1': globalvar.dict_dataframe_kline_M1[InstrumentID],
                                       'K线周期: M3': globalvar.dict_dataframe_kline_M3[InstrumentID],
                                       'K线周期: M5': globalvar.dict_dataframe_kline_M5[InstrumentID],
                                       'K线周期: M10': globalvar.dict_dataframe_kline_M10[InstrumentID],
                                       'K线周期: M15': globalvar.dict_dataframe_kline_M15[InstrumentID],
                                       'K线周期: M30': globalvar.dict_dataframe_kline_M30[InstrumentID],
                                       'K线周期: M60': globalvar.dict_dataframe_kline_M60[InstrumentID],
                                       'K线周期: M120': globalvar.dict_dataframe_kline_M120[InstrumentID],
                                       'K线周期: D1': globalvar.dict_dataframe_kline_D1[InstrumentID]
                                       }
        try:
            if not os.path.exists(("dataframe_kline\\" + InstrumentID)):
                os.mkdir("dataframe_kline\\" + InstrumentID)
            globalvar.dict_dataframe_kline_M1[InstrumentID].to_csv(
                "dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index=False)
            data = pd.read_csv("dataframe_kline\\" + InstrumentID + "\\kline_1min.csv", index_col='datetime',
                               parse_dates=True)
            grouper = data.groupby(
                [pd.Grouper(freq=period_type), 'recordid', 'tradingday', 'klinetime', 'instrumentid', 'open', 'close',
                 'low', 'high',
                 'vol'])
            df = pd.DataFrame(grouper['instrumentid'].count())
            df.rename(columns={'instrumentid': 'count'}, inplace=True)
            df.reset_index(inplace=True)
            del df['count']
            df2 = pd.DataFrame(
                {"datetime": [], 'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [],
                 'close': [],
                 'low': [], 'high': [],
                 'vol': []}, index=[])

            lastdatetime = ""
            high = 0
            low = 0
            open = 0
            close = 0
            vol = 0
            instrumentid = ""
            datetime = ""
            tradingday = ""
            klinetime = ""
            recordid = 1
            for index, row in df.iterrows():
                QApplication.processEvents()
                if lastdatetime != str(row['datetime']):
                    if open > 0:
                        tempdata = {"datetime": datetime, "recordid": '{:0>8s}'.format(str(recordid)),
                                    "tradingday": tradingday, "klinetime": klinetime,
                                    "instrumentid": instrumentid,
                                    "open": open, "close": close, "low": low, "high": high, "vol": vol}
                        df2 = df2.append(tempdata, ignore_index=True)
                    recordid = int(row['recordid'])
                    open = float(row['open'])
                    low = float(row['low'])
                    high = float(row['high'])
                    close = float(row['close'])
                    vol = int(row['vol'])
                    lastdatetime = str(row['datetime'])
                    lastclose = row['close']
                    datetime = row['datetime']
                    instrumentid = row['instrumentid']
                    tradingday = row['tradingday']
                    klinetime = row['klinetime']
                else:
                    recordid = int(row['recordid'])
                    low = min(low, float(row['low']))
                    high = max(high, float(row['high']))
                    close = float(row['close'])
                    vol = vol + int(row['vol'])

            df2 = df2.sort_values(by='recordid')
            df2.to_csv("dataframe_kline\\" + InstrumentID + "\\kline_" + period_type + ".csv", index=True)
            dict_period_dataframe_kline[period_type] = df2.copy()
            # 更新K线图表
            # self.UpdateKlineChartsBycombox(InstrumentID, period_type, dict_period_dataframe_kline[period_type])
            # self.GetKlineFromeMemory(dict_period_dataframe_kline[period_type],period_type)
        except Exception as e:
            print("combineklineBackgroundCal Error:" + repr(e))

    def to_comboBox_klineperiod(self, text):
        globalvar.selectperiod = self.dict_period3[text]
        print('globalvar.selectperiod: ' + str(globalvar.selectperiod))
        print('globalvar.selectinstrumenid: ' + str(globalvar.selectinstrumenid))
        print('self.dict_period[text]: ' + str(self.dict_period[text]))
        self.combineklineUpdateCharts(globalvar.selectinstrumenid, self.dict_period[text])

    def ChangePeriodCharts_klineperiod(self, period):
        self.combineklineUpdateCharts(globalvar.selectinstrumenid, self.dict_period2[period])

    def Background_klineperiod(self):
        self.combineklineBackgroundCal(globalvar.selectinstrumenid)

    def to_comboBox_1(self, text):
        self.comboBox_instrument.clear()
        self.comboBox_instrumentid.clear()
        templist = text.split(",", -1)
        # templist2 = []
        # self.MakeInsutrumentID(templist[0],templist[1],templist[2],templist2)
        # self.comboBox_instrumentid.addItems(templist2)
        if templist[0] == 'ALL':
            self.comboBox_instrument.addItems(globalvar.list_INE)
            self.comboBox_instrument.addItems(globalvar.list_CFFEX)
            self.comboBox_instrument.addItems(globalvar.list_SHFE)
            self.comboBox_instrument.addItems(globalvar.list_DCE)
            self.comboBox_instrument.addItems(globalvar.list_CZCE)
        elif templist[0] == 'INE':
            self.comboBox_instrument.addItems(globalvar.list_INE)
            if len(globalvar.list_INE) > 0:
                templist2 = globalvar.list_INE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_INE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'CFFEX':
            self.comboBox_instrument.addItems(globalvar.list_CFFEX)
            if len(globalvar.list_CFFEX) > 0:
                templist2 = globalvar.list_CFFEX[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_CFFEX[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'SHFE':
            self.comboBox_instrument.addItems(globalvar.list_SHFE)
            if len(globalvar.list_SHFE) > 0:
                templist2 = globalvar.list_SHFE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_SHFE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'DCE':
            self.comboBox_instrument.addItems(globalvar.list_DCE)
            if len(globalvar.list_DCE) > 0:
                templist2 = globalvar.list_DCE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_DCE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        elif templist[0] == 'CZCE':
            self.comboBox_instrument.addItems(globalvar.list_CZCE)
            if len(globalvar.list_CZCE) > 0:
                templist2 = globalvar.list_CZCE[0].split(",", -1)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
                self.comboBox_instrumentid.clear()
                templist = globalvar.list_CZCE[0].split(",", -1)
                templist2 = []
                self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
                self.comboBox_instrumentid.addItems(templist2)
                globalvar.selectinstrumenid = templist2[0]
                globalvar.rc.updatehistorystock(templist2[0])
        self.GetKlineFromeServer()

    def to_comboBox_2(self, text):
        self.comboBox_instrumentid.clear()
        templist = text.split(",", -1)
        templist2 = []
        self.MakeInsutrumentID(templist[0], templist[1], templist[2], templist2)
        self.comboBox_instrumentid.addItems(templist2)
        globalvar.selectinstrumenid = templist2[0]
        globalvar.rc.updatehistorystock(templist2[0])
        if templist[2] == 'ALL':
            self.comboBox_exchange.setCurrentText(templist[2] + ',全部交易所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'INE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',能源所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'CFFEX':
            self.comboBox_exchange.setCurrentText(templist[2] + ',中金所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'SHFE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',上期所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'DCE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',大商所')
            globalvar.selectexchange = templist[2]
        elif templist[2] == 'CZCE':
            self.comboBox_exchange.setCurrentText(templist[2] + ',郑商所')
            globalvar.selectexchange = templist[2]
        self.GetKlineFromeServer()

    def to_comboBox_3(self, text):
        globalvar.selectinstrumenid = text
        globalvar.rc.updatehistorystock(text)
        self.GetKlineFromeServer()

    def change_comboBox(self, text):
        global dict_instrument, dict_instrument
        globalvar.rc.updatehistorystock(text)
        if text in globalvar.dict_exchange:
            self.comboBox_exchange.setCurrentText(str(globalvar.dict_exchange[text]))
            self.to_comboBox_1(str(globalvar.dict_exchange[text]))
            self.comboBox_instrument.setCurrentText(str(globalvar.dict_instrument[text]))
            self.to_comboBox_2(str(globalvar.dict_instrument[text]))
            self.comboBox_instrumentid.setCurrentText(text)
            self.to_comboBox_3(text)

    def callback_md_combox(self):
        self.comboBox_instrument.addItems(globalvar.list_INE)
        self.comboBox_instrument.addItems(globalvar.list_CFFEX)
        self.comboBox_instrument.addItems(globalvar.list_SHFE)
        self.comboBox_instrument.addItems(globalvar.list_DCE)
        self.comboBox_instrument.addItems(globalvar.list_CZCE)

    # 打开资金曲线对话框
    def Function_OpenCapitalCurve(self):
        ui_demo = self.DialogCapitalCurve()
        ui_demo.centralWidget()
        # 居中窗口
        screen = QDesktopWidget().screenGeometry()
        size = ui_demo.geometry()
        ui_demo.move((screen.width() - size.width()) / 2 - 75,
                     (screen.height() - size.height()) / 2 - 50)
        ui_demo.setWindowTitle('添加交易账户')
        ui_demo.show()
        ui_demo.resize(450, 300)
        # self.childwidget = self.childwidget(self)
        # self.childwidget.exec_()
        ui_demo.exec_()

    def Function_OpenUrl_SIMNOW(self):
        # QtWidgets.QMessageBox.warning(self, "Warning", "输入数据错误，请重新输入！",QMessageBox.Yes)
        self.autologoutwarnwin = QMessageBox(None)
        self.autologoutwarnwin.setIcon(QMessageBox.Warning)
        self.autologoutwarnwin.setText(('上期SIMNOW官网提供CTP模拟账户注册，\n网站只能在工作日白天才能访问。\n\n但模拟交易账户注册成功后，\n和实盘账户交易时间是一致的。'))
        self.autologoutwarnwin.setWindowTitle(('说明'))
        self.autologoutwarnwin.setStandardButtons(QMessageBox.Ok)
        self.buttonOK = self.autologoutwarnwin.button(QMessageBox.Ok)
        self.buttonOK.setText('我知道了,打开上期SIMNOW网站')
        # self.autologoutwarnwin.buttonClicked.connect(self.autologoutwarn_accepted)
        self.autologoutwarnwin.exec_()
        webbrowser.open('http://www.simnow.com.cn/')

    def Function_OpenUrl_VNPY(self):
        webbrowser.open('http://www.vnpy.cn/')

    def Function_OpenUrl_VNTRADER(self):
        webbrowser.open('http://www.vntrader.cn/')

    def Function_OpenUrl_ZHIHU(self):
        webbrowser.open('https://www.zhihu.com/org/vnpy/posts')

    def Function_OpenUrl_ZHIHUVIDEO(self):
        webbrowser.open('https://www.zhihu.com/org/vnpy/zvideos/')

    def Function_OpenUrl_COOLQUANT(self):
        webbrowser.open('http://www.coolquant.cn/')

    def Function_OpenUrl_KAIHU(self):
        webbrowser.open('http://www.kaihucn.cn/')

    def Function_OpenUrl_Plus(self):
        webbrowser.open('http://www.vnpy.cn/qplus.html')

    def Function_OpenUrl_Community(self):
        webbrowser.open('http://q.vnpy.cn/')

    def Function_OpenUrl_Buyplus(self):
        webbrowser.open('http://q.vnpy.cn/')

    def Function_KlineSource_ServerToday(self):
        self.Button_KlineSource_ServerToday.setChecked(True)
        self.Button_KlineSource_ServerMultiday.setChecked(False)
        globalvar.klineserverstate = 1
        self.GetKlineFromeServer()

    def Function_KlineSource_ServerMultiday(self):
        self.Button_KlineSource_ServerToday.setChecked(False)
        self.Button_KlineSource_ServerMultiday.setChecked(True)
        globalvar.klineserverstate = 2
        self.GetKlineFromeServer()

    def Function_Buttonclickh1(self):
        try:
            if '最近访问' in self.Button_h[0].text():
                return
            else:
                self.change_comboBox(self.Button_h[0].text())
        except Exception as e:
            print("Function_Buttonclickh1:" + repr(e))

    def setupUi(self, MainWindow):
        self.MainWindow = MainWindow
        self.MainWindow.setObjectName("MainWindow")

        self.tabWidget = QtWidgets.QTabWidget()
        self.tabWidget.setTabPosition(QtWidgets.QTabWidget.East)
        self.tabWidget.setTabsClosable(True)
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.gridLayout = QtWidgets.QGridLayout(self.tab)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")

        self.tab_instrument = QtWidgets.QWidget()
        self.tab_instrument.setObjectName("tab_instrument")
        self.gridLayout_instrument = QtWidgets.QGridLayout(self.tab_instrument)
        self.gridLayout_instrument.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_instrument.setObjectName("gridLayout_tab_instrument")
        self.table_instrument = QtWidgets.QTableWidget(self.tab_instrument)
        self.table_instrument.setObjectName("table_instrument")
        self.table_instrument.verticalHeader().setVisible(False)  # 隐藏垂直表头
        self.table_instrument.horizontalHeader().setVisible(True)  # 隐藏水平表头
        self.table_instrument.setEditTriggers(QTableView.NoEditTriggers)
        self.table_instrument.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_instrument.setColumnCount(7)
        self.table_instrument.setRowCount(0)
        self.table_instrument.setHorizontalHeaderLabels(
            ['ID', '合约', '合约编码', '交易所', '1跳价差', '保证金', '手续费'])  # 设置表头文字
        self.table_instrument.setSortingEnabled(True)  # 设置表头可以自动排序

        Trade_InstrumentBtn = QtWidgets.QPushButton('合约设置')
        Trade_InstrumentBtn.setFlat(True)
        Trade_InstrumentBtn.setStyleSheet('background-color:#ff0000;')
        Trade_InstrumentBtn.setStyleSheet('QPushButton{margin:3px}')

        self.tabWidget.addTab(self.tab, "")

        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1068, 23))
        self.menubar.setObjectName("menubar")
        self.menuMenu_nav3 = QtWidgets.QMenu(self.menubar)
        self.menuMenu_nav3.setObjectName("menuMenub")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.dockWidget1 = QtWidgets.QDockWidget(MainWindow)
        self.dockWidget1.setObjectName("dockWidget1")
        # self.dockWidget1.setFixedSize(800, QDesktopWidget().availableGeometry().height() - 20)  # 分别为宽度和高度

        MainWindow.setFixedSize(QDesktopWidget().availableGeometry().width(),
                                QDesktopWidget().availableGeometry().height())

        self.dockWidgetContents = QtWidgets.QWidget()
        self.dockWidgetContents.setObjectName("dockWidgetContents")

        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.dockWidgetContents)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.comboBox_kline = QtWidgets.QComboBox()
        # self.comboBox_kline.setFixedWidth(180)
        self.comboBox_kline.setObjectName("comboBox_kline")
        self.comboBox_kline.setFixedWidth(180)
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.comboBox_kline.addItem("")
        self.verticalLayout.addWidget(self.comboBox_kline)
        self.verticalLayout.addStretch(1)  # 与上面1：1 空白拉伸

        self.comboBox_exchange = QtWidgets.QComboBox()
        self.comboBox_exchange.setFixedWidth(180)
        self.comboBox_exchange.setObjectName("comboBox_exchange")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.comboBox_exchange.addItem("")
        self.verticalLayout.addWidget(self.comboBox_exchange)
        self.verticalLayout.addStretch(1)  # 与上面1：1 空白拉伸

        self.comboBox_instrument = QtWidgets.QComboBox()
        self.comboBox_instrument.setFixedWidth(180)
        self.comboBox_instrument.setObjectName("comboBox_instrument")
        self.comboBox_instrument.addItem("选择合约类型编码")
        self.verticalLayout.addWidget(self.comboBox_instrument)
        self.verticalLayout.addStretch(1)  # 与上面1：1 空白拉伸

        self.comboBox_instrumentid = QtWidgets.QComboBox()
        self.comboBox_instrumentid.setFixedWidth(180)
        self.comboBox_instrumentid.setObjectName("comboBox_instrumentid")

        self.comboBox_kline.activated.connect(lambda: self.to_comboBox_klineperiod(self.comboBox_kline.currentText()))
        self.comboBox_exchange.activated.connect(lambda: self.to_comboBox_1(self.comboBox_exchange.currentText()))
        self.comboBox_instrument.activated.connect(lambda: self.to_comboBox_2(self.comboBox_instrument.currentText()))
        self.comboBox_instrumentid.activated.connect(
            lambda: self.to_comboBox_3(self.comboBox_instrumentid.currentText()))

        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.frame_comboBox = QtWidgets.QFrame(self.comboBox_kline)
        self.frame_comboBox.setMinimumSize(QtCore.QSize(0, 0))
        self.frame_comboBox.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_comboBox.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_comboBox.setLineWidth(3)
        self.frame_comboBox.setObjectName("frame_comboBox")
        self.verticalLayout.addWidget(self.frame_comboBox)

        self.gridLayout_comboBox = QtWidgets.QGridLayout(self.frame_comboBox)
        self.gridLayout_comboBox.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_comboBox.setObjectName("gridLayout_optionalstock222")

        self.gridLayout_comboBox.addWidget(self.comboBox_kline, 4, 0, 1, 1)
        self.gridLayout_comboBox.addWidget(self.comboBox_exchange, 4, 1, 1, 1)
        self.gridLayout_comboBox.addWidget(self.comboBox_instrument, 4, 2, 1, 1)
        self.gridLayout_comboBox.addWidget(self.comboBox_instrumentid, 4, 3, 1, 1)

        # K线图位置
        # global logYdata
        self.item = CandlestickItem(data_kline)  # 原始数据,对应（0,0）幅图
        npdata = np.array(data_kline)
        # logYdata = np.log(npdata[:, 1:])
        # self.logYdata = np.log(npdata[1:, 2:])
        # self.logYdata = np.insert(self.logYdata, 0, values=npdata[:, 0], axis=1)
        # self.logYdata = list(map(tuple, self.logYdata))
        self.wkline = pg.GraphicsWindow()
        self.wkline.setWindowTitle('主视图K线图')
        self.plt_kline = self.wkline.addPlot(1, 1, title="K线图")
        self.plt_kline.addItem(self.item)
        self.plt_kline.showGrid(True, True)
        self.plt_kline.setMouseEnabled(x=True, y=True)  # 禁用轴操作
        self.verticalLayout.addWidget(self.wkline)
        self.wkline.showMaximized()
        # K线图位置

        self.Button_h = []

        self.temps = QtWidgets.QPushButton('最近访问1')
        self.temps.setObjectName("Button_h1")
        self.temps.clicked.connect(self.Function_Buttonclickh1)
        self.Button_h.append(self.temps)

        self.frame = QtWidgets.QFrame(self.Button_h[0])
        self.frame.setMinimumSize(QtCore.QSize(0, 0))
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setLineWidth(3)
        self.frame.setObjectName("frame")
        self.verticalLayout.addWidget(self.frame)

        self.gridLayout_optionalstock = QtWidgets.QGridLayout(self.frame)
        self.gridLayout_optionalstock.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_optionalstock.setObjectName("gridLayout_optionalstock")

        geo = self.Button_h[0].geometry()
        geo.moveCenter(self.frame.rect().center())

        self.verticalLayout_2.addWidget(self.frame)
        self.dockWidget1.setWidget(self.dockWidgetContents)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.dockWidget1)
        self.toolBar = QtWidgets.QToolBar(MainWindow)
        self.toolBar.setObjectName("toolBar")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)

        # 左边行情滚动位置

        self.Button_OpenDll = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_OpenDll.setObjectName("Button_OpenDll")
        self.Button_CloseDll = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_CloseDll.setObjectName("Button_CloseDll")
        self.Button_StrategyManage_SingleThread = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_StrategyManage_SingleThread.setObjectName("Button_StrategyManage_SingleThread")
        self.Button_StrategyManage_MulitProcess = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_StrategyManage_MulitProcess.setObjectName("Button_StrategyManage_MulitProcess")
        self.Button_KlineSource_ServerToday = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_KlineSource_ServerToday.setObjectName("Button_KlineSource_ServerToday")
        self.Button_KlineSource_ServerMultiday = QtWidgets.QAction(MainWindow, checkable=True)
        self.Button_KlineSource_ServerMultiday.setObjectName("Button_KlineSource_ServerMultiday")
        self.Button_CloseDll.setChecked(True)
        self.Button_StrategyManage_SingleThread.setChecked(True)

        self.Navgiate1 = QtWidgets.QAction(MainWindow)
        self.Navgiate1.setObjectName("Navgiate1")
        self.Navgiate2 = QtWidgets.QAction(MainWindow)
        self.Navgiate2.setObjectName("Navgiate2")
        self.Navgiate3 = QtWidgets.QAction(MainWindow)
        self.Navgiate3.setObjectName("Navgiate3")
        self.Navgiate4 = QtWidgets.QAction(MainWindow)
        self.Navgiate4.setObjectName("Navgiate4")
        self.Navgiate5 = QtWidgets.QAction(MainWindow)
        self.Navgiate5.setObjectName("Navgiate5")
        self.Navgiate6 = QtWidgets.QAction(MainWindow)
        self.Navgiate6.setObjectName("Navgiate6")
        self.Navgiate7 = QtWidgets.QAction(MainWindow)
        self.Navgiate7.setObjectName("Navgiate7")
        self.Navgiate8 = QtWidgets.QAction(MainWindow)
        self.Navgiate8.setObjectName("Navgiate8")
        self.Navgiate1_C = QtWidgets.QAction(MainWindow)
        self.Navgiate1_C.setObjectName("Navgiate1_C")

        self.menuMenu_nav3.addAction(self.Button_KlineSource_ServerToday)
        self.menuMenu_nav3.addAction(self.Button_KlineSource_ServerMultiday)
        self.menubar.addAction(self.menuMenu_nav3.menuAction())

        self.toolBar.addAction(self.Navgiate1)
        self.toolBar.addAction(self.Navgiate2)
        self.toolBar.addAction(self.Navgiate3)
        self.toolBar.addAction(self.Navgiate4)
        self.toolBar.addAction(self.Navgiate5)
        self.toolBar.addAction(self.Navgiate6)
        self.toolBar.addAction(self.Navgiate7)
        self.toolBar.addAction(self.Navgiate8)
        self.retranslateUi(MainWindow)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    # 从文件读取更新当日K线图
    def UpdateKlineUIFromFile(self, InstrumentID, TradingDay):
        try:
            global kid, count
            kid = 1
            fname = globalvar.currpath + "\\data_today\\" + InstrumentID + ".csv"
            print('filename: ' + fname)
            globalvar.ticklist = []
            if os.path.isfile(fname):
                for line in open(fname):
                    QApplication.processEvents()
                    ld = line.split(',')
                    temp = (kid,
                            float(ld[0]),
                            float(ld[1]),
                            float(ld[3]),
                            float(ld[4]),
                            float(ld[5]),
                            int(ld[6]))
                    globalvar.data_kline_M1.append(temp)

                    tempstr = str(int(float(ld[1]) * 10000))
                    tempstr_list = list(tempstr)
                    tempstr_list.insert(len(tempstr_list) - 2, ':')
                    tempstr = ''.join(tempstr_list)
                    globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                    '''
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                        {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                         'vol': []}, index=[])
                    '''
                    ld[1] = ld[1].ljust(8, '0')
                    ld[1] = '{:0>8s}'.format(ld[1])
                    tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                            4:6] + ":" + \
                                ld[1][6:8]
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                        InstrumentID].append({
                        'datetime': tdatetime,
                        'recordid': '{:0>8s}'.format(str(kid)),
                        'tradingday': ld[0],
                        'klinetime': ld[1],
                        'instrumentid': ld[2],
                        'open': float(ld[3]),
                        'close': float(ld[4]),
                        'low': float(ld[5]),
                        'high': float(ld[6]),
                        'vol': int(ld[7]),
                    }, ignore_index=True)
                    kid = kid + 1
            self.plt_kline.removeItem(self.item)

            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
            try:
                self.plt_kline.addItem(self.item)
                count += 1
            except Exception as e:
                print("UpdateKlineUIFromFileB Error:" + repr(e))

            # 横坐标刻度
            xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
            xdict = dict(enumerate(globalvar.ticklist))
            xax.setTicks([xdict.items()])

            # 根据M1周期K线合成M3周期K线数据
            # module_combinekline.ComposeKlineUpdate(InstrumentID, "3min")
        except Exception as e:
            print("UpdateKlineUIFromFile Error:" + repr(e))

    def UpdateKlineUIFromFileBakUp(self, InstrumentID, TradingDay):
        try:
            global kid, count
            kid = 1
            fname = globalvar.currpath + "\\data_today\\" + InstrumentID + ".csv"
            print('filename: ' + fname)
            globalvar.ticklist = []
            if os.path.isfile(fname):
                for line in open(fname):
                    ld = line.split(',')
                    temp = (kid,
                            float(ld[0]),
                            float(ld[1]),
                            float(ld[3]),
                            float(ld[4]),
                            float(ld[5]),
                            int(ld[6]))
                    globalvar.data_kline_M1.append(temp)

                    tempstr = str(int(float(ld[1]) * 10000))
                    tempstr_list = list(tempstr)
                    tempstr_list.insert(len(tempstr_list) - 2, ':')
                    tempstr = ''.join(tempstr_list)
                    globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                    '''
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                        {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                         'vol': []}, index=[])
                    '''
                    ld[1] = ld[1].ljust(8, '0')
                    ld[1] = '{:0>8s}'.format(ld[1])
                    tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                            4:6] + ":" + \
                                ld[1][6:8]
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                        InstrumentID].append({
                        'datetime': tdatetime,
                        'recordid': '{:0>8s}'.format(str(kid)),
                        'tradingday': ld[0],
                        'klinetime': ld[1],
                        'instrumentid': ld[2],
                        'open': float(ld[3]),
                        'close': float(ld[4]),
                        'low': float(ld[5]),
                        'high': float(ld[6]),
                        'vol': int(ld[7]),
                    }, ignore_index=True)
                    kid = kid + 1
            self.plt_kline.removeItem(self.item)

            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
            try:
                self.plt_kline.addItem(self.item)
                count += 1
            except Exception as e:
                print("UpdateKlineUIFromFileB Error:" + repr(e))

            # 横坐标刻度
            xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
            xdict = dict(enumerate(globalvar.ticklist))
            xax.setTicks([xdict.items()])

            # 根据M1周期K线合成M3周期K线数据
            # module_combinekline.ComposeKlineUpdate(InstrumentID, "3min")


        except Exception as e:
            print("UpdateKlineUIFromFile Error:" + repr(e))

    def dateprevious(self, year, mouth, day):
        list_mouth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if day == 1:
            if mouth == 1:
                year = year - 1
                mouth = 12
                day = list_mouth[mouth - 1]
            else:
                mouth = mouth - 1
                day = list_mouth[mouth - 1]
                if day == 28:
                    if year % 4 == 0:
                        day = 29
        else:
            day = day - 1
        return year * 10000 + mouth * 100 + day

    # 从文件读取更新多日M1 K线图
    def UpdateMultiKlineUIFromFile(self, InstrumentID, TradingDay):
        global kid
        kid = 1
        TradingDaylist = []
        globalvar.ticklist = []
        newTradingDay = TradingDay
        for addday in range(10):
            tyear = int(str(newTradingDay)[0:4])
            tmonth = int(str(newTradingDay)[4:6])
            tday = int(str(newTradingDay)[6:8])
            newTradingDay = self.dateprevious(tyear, tmonth, tday)
            TradingDaylist.append(newTradingDay)
        TradingDaylist.reverse()
        for addday in range(10):
            fname = globalvar.currpath + "\\data_multiday\\" + InstrumentID + "\\" + str(
                TradingDaylist[addday]) + ".csv"
            if os.path.isfile(fname):
                for line in open(fname):
                    QApplication.processEvents()
                    ld = line.split(',')
                    temp = (kid,
                            float(ld[0]),
                            float(ld[1]),
                            float(ld[3]),
                            float(ld[4]),
                            float(ld[5]),
                            int(ld[6]))
                    globalvar.data_kline_M1.append(temp)

                    tempstr = str(int(float(ld[1]) * 10000))
                    tempstr_list = list(tempstr)
                    tempstr_list.insert(len(tempstr_list) - 2, ':')
                    tempstr = ''.join(tempstr_list)
                    globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                    '''
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                        {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                         'vol': []}, index=[])
                    '''
                    ld[1] = ld[1].ljust(8, '0')
                    ld[1] = '{:0>8s}'.format(ld[1])
                    tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                            4:6] + ":" + \
                                ld[1][6:8]
                    globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                        InstrumentID].append({
                        'datetime': tdatetime,
                        # 'recordid': ld[0] + str(kid),
                        'recordid': '{:0>8s}'.format(str(kid)),
                        'tradingday': ld[0],
                        'klinetime': ld[1],
                        'instrumentid': ld[2],
                        'open': float(ld[3]),
                        'close': float(ld[4]),
                        'low': float(ld[5]),
                        'high': float(ld[6]),
                        'vol': int(ld[7]),
                    }, ignore_index=True)

                    kid = kid + 1
        fname = globalvar.currpath + "\\data_multiday\\" + InstrumentID + "\\" + str(TradingDay) + ".csv"

        if os.path.isfile(fname):
            for line in open(fname):
                QApplication.processEvents()
                ld = line.split(',')
                temp = (kid,
                        float(ld[0]),
                        float(ld[1]),
                        float(ld[3]),
                        float(ld[4]),
                        float(ld[5]),
                        int(ld[6]))
                globalvar.data_kline_M1.append(temp)

                tempstr = str(int(float(ld[1]) * 10000))
                tempstr_list = list(tempstr)
                tempstr_list.insert(len(tempstr_list) - 2, ':')
                tempstr = ''.join(tempstr_list)

                globalvar.ticklist.append(ld[0] + "\n" + tempstr)

                '''
                globalvar.dict_dataframe_kline_M1[InstrumentID] = pd.DataFrame(
                    {'datetime': [],'recordid': [], 'tradingday': [], 'klinetime': [], 'instrumentid': [], 'open': [], 'close': [], 'low': [], 'high': [],
                     'vol': []}, index=[])
                '''

                ld[1] = ld[1].ljust(8, '0')
                ld[1] = '{:0>8s}'.format(ld[1])
                tdatetime = ld[0][0:4] + "-" + ld[0][4:6] + "-" + ld[0][6:8] + " " + ld[1][2:4] + ":" + ld[1][
                                                                                                        4:6] + ":" + ld[
                                                                                                                         1][
                                                                                                                     6:8]
                globalvar.dict_dataframe_kline_M1[InstrumentID] = globalvar.dict_dataframe_kline_M1[
                    InstrumentID].append({
                    'datetime': tdatetime,
                    'recordid': '{:0>8s}'.format(str(kid)),
                    'tradingday': ld[0],
                    'klinetime': ld[1],
                    'instrumentid': ld[2],
                    'open': float(ld[3]),
                    'close': float(ld[4]),
                    'low': float(ld[5]),
                    'high': float(ld[6]),
                    'vol': int(ld[7]),
                }, ignore_index=True)

                kid = kid + 1
        self.plt_kline.removeItem(self.item)
        self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
        # npdata = np.array(globalvar.data_kline_M1)
        try:
            self.plt_kline.addItem(self.item)
            count += 1
        except Exception as e:
            print("UpdateMultiKlineUIFromFile Error:" + repr(e))
        # globalvar.dict_data_kline_M1[InstrumentID] = globalvar.data_kline_M1.copy()

        # 横坐标刻度
        xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
        xdict = dict(enumerate(globalvar.ticklist))
        xax.setTicks([xdict.items()])

        # 根据M1周期K线合成M3周期K线数据
        # module_combinekline.ComposeKlineUpdate(InstrumentID, "3min")

    # 更新K线图
    def updateklineUi(self, InstrumentID):
        if globalvar.md:
            try:
                global lasttime
                global kid, count
                kid = kid + 1
                if lasttime != globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime:
                    lasttime = globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime
                    thiskid = globalvar.data_kline_M1[len(globalvar.data_kline_M1) - 1][0] + 1
                    temp = (
                        thiskid,
                        float(globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay.decode('utf-8')),
                        globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime,
                        globalvar.md.GetKline(InstrumentID, 1).contents.Open,
                        globalvar.md.GetKline(InstrumentID, 1).contents.Close,
                        globalvar.md.GetKline(InstrumentID, 1).contents.Low,
                        globalvar.md.GetKline(InstrumentID, 1).contents.High
                        # globalvar.md.GetKline(InstrumentID, 1).contents.Volume
                    )

                    globalvar.data_kline_M1.append(temp)
                    tempstr = str(int(float(globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay)))
                    tempstr_list = list(tempstr)
                    tempstr = ''.join(tempstr_list)
                    klinetimestr = str(globalvar.md.GetKline(InstrumentID, 1).contents.KlineTime)
                    globalvar.ticklist.append(tempstr + "\n" + klinetimestr)
                    TradingDay = str(globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay,
                                     encoding="utf-8").ljust(8, '0')
                    TradingDay = '{:0>8s}'.format(TradingDay)
                    tdatetime = klinetimestr[0:4] + "-" + klinetimestr[4:6] + "-" + klinetimestr[
                                                                                    6:8] + " " + TradingDay[
                                                                                                 2:4] + ":" + TradingDay[
                                                                                                              4:6] + ":" + TradingDay[
                                                                                                                           6:8]
                    try:
                        if globalvar.notfirstupdateklineUi:
                            InstrumentID_key = InstrumentID.decode('utf-8')
                            globalvar.dict_dataframe_kline_M1[InstrumentID_key] = globalvar.dict_dataframe_kline_M1[
                                InstrumentID_key].append({
                                'datetime': tdatetime,
                                'recordid': '{:0>8s}'.format(str(thiskid)),
                                'tradingday': float(
                                    globalvar.md.GetKline(InstrumentID, 1).contents.TradingDay.decode('utf-8')),
                                'klinetime': klinetimestr,
                                'instrumentid': InstrumentID,
                                'open': globalvar.md.GetKline(InstrumentID, 1).contents.Open,
                                'close': globalvar.md.GetKline(InstrumentID, 1).contents.Close,
                                'low': globalvar.md.GetKline(InstrumentID, 1).contents.Low,
                                'high': globalvar.md.GetKline(InstrumentID, 1).contents.High,
                                'vol': globalvar.md.GetKline(InstrumentID, 1).contents.Volume,
                            }, ignore_index=True)
                            self.plt_kline.removeItem(self.item)
                            self.item = CandlestickItem(globalvar.data_kline_M1)  # 原始数据,对应（0,0）幅图
                        else:
                            globalvar.notfirstupdateklineUi = True
                    except Exception as e: \
                            print("dict_dataframe_kline_M1 No Key:" + repr(e))

                    try:
                        self.plt_kline.addItem(self.item)
                        count += 1
                    except Exception as e:
                        print("UpdateKlineUIFromFileB Error:" + repr(e))
                    # 横坐标刻度
                    xax = self.plt_kline.getAxis('bottom')  # 坐标轴x
                    xdict = dict(enumerate(globalvar.ticklist))
                    xax.setTicks([xdict.items()])
                    # 根据M1周期K线合成M3周期K线数据
                    # module_combinekline.ComposeKlineUpdate(InstrumentID, "3min")
            except Exception as e:
                print("updateklineUi Error:" + repr(e))

    # 更新分时图
    def updatemarketUi(self, newdata):
        def update_market(newdata):
            global data_market, count
            data_market.append(newdata)
            if len(data_market) > 1000:
                data_market.pop(0)
            self.curve_market.setData(np.hstack(data_market))
            count += 1

        update_market(newdata)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        # 交易信息

        self.menuMenu_nav3.setTitle(_translate("MainWindow", "&K线数据来源"))
        # self.dockWidget1.setWindowTitle(_translate("MainWindow", "&Dock widget 1"))
        self.dockWidget1.setWindowTitle(_translate("MainWindow", "KlineService 是VNPY（www.vnpy.cn提供的免费期货K线调用服务）"))
        self.dockWidget1.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.comboBox_kline.setItemText(0, _translate("MainWindow", "K线周期: M1"))
        self.comboBox_kline.setItemText(1, _translate("MainWindow", "K线周期: M3"))
        self.comboBox_kline.setItemText(2, _translate("MainWindow", "K线周期: M5"))
        self.comboBox_kline.setItemText(3, _translate("MainWindow", "K线周期: M10"))
        self.comboBox_kline.setItemText(4, _translate("MainWindow", "K线周期: M15"))
        self.comboBox_kline.setItemText(5, _translate("MainWindow", "K线周期: M30"))
        self.comboBox_kline.setItemText(6, _translate("MainWindow", "K线周期: M60"))
        self.comboBox_kline.setItemText(7, _translate("MainWindow", "K线周期: D1"))
        self.comboBox_exchange.setItemText(0, _translate("MainWindow", "ALL,全部交易所"))
        self.comboBox_exchange.setItemText(1, _translate("MainWindow", "SHFE,上期所"))
        self.comboBox_exchange.setItemText(2, _translate("MainWindow", "DCE,大商所"))
        self.comboBox_exchange.setItemText(3, _translate("MainWindow", "CZCE,郑商所"))
        self.comboBox_exchange.setItemText(4, _translate("MainWindow", "CFFEX,中金所"))
        self.comboBox_exchange.setItemText(5, _translate("MainWindow", "INE,能源所"))
        self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))

        self.Navgiate1.setText(_translate("MainWindow", "&VNPY官网"))
        self.Navgiate2.setText(_translate("MainWindow", "&VNTrader官网"))
        self.Navgiate3.setText(_translate("MainWindow", "&VNPY知乎"))
        self.Navgiate4.setText(_translate("MainWindow", "&知乎视频"))
        self.Navgiate5.setText(_translate("MainWindow", "&期货低佣金开户"))
        self.Navgiate6.setText(_translate("MainWindow", "&量化资源列表"))
        self.Navgiate2.setToolTip(_translate("MainWindow", "submenu"))
        self.Navgiate1_C.setText(_translate("MainWindow", "一键平仓"))

        self.Button_KlineSource_ServerToday.setText(_translate("MainWindow", "&实时TICK生成K线 + 从服务器补齐1日K线"))
        self.Button_KlineSource_ServerMultiday.setText(
            _translate("MainWindow", "&实时TICK生成K线 + 从服务器补齐多日K线（增值服务Plus会员激活）"))
        self.Navgiate1.triggered.connect(self.Function_OpenUrl_VNPY)
        self.Navgiate2.triggered.connect(self.Function_OpenUrl_VNTRADER)
        self.Navgiate3.triggered.connect(self.Function_OpenUrl_ZHIHU)
        self.Navgiate4.triggered.connect(self.Function_OpenUrl_ZHIHUVIDEO)
        self.Navgiate5.triggered.connect(self.Function_OpenUrl_KAIHU)
        self.Navgiate6.triggered.connect(self.Function_OpenUrl_COOLQUANT)

        self.Button_KlineSource_ServerToday.triggered.connect(self.Function_KlineSource_ServerToday)
        self.Button_KlineSource_ServerMultiday.triggered.connect(self.Function_KlineSource_ServerMultiday)
